package zjf.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import zjf.util.OperationUtil;
import zjf.util.StringUtil;
import zjf.vo.AdvancedUtil;
import zjf.vo.SNSUserInfo;
import zjf.vo.WeixinContons;
import zjf.vo.WeixinOauth2Token;



public class PageAction extends BaseAction {
	private static final Log log = LogFactory
			.getLog(PageAction.class);
//	private boolean tag=true;
	private boolean tag=false;
	public String page;

	public String getPage() {
		return page;
	}
	public void setPage(String page) {
		this.page = page;
	}

	/**
	 * 页面跳转
	 * 
	 * @return
	 * @throws Exception
	 */
	public String forwardPage() {
		System.out.println("page:"+WeixinContons.APPID);
		String openId=null;
		String url=getRequest().getRequestURI().split("forwardPage_")[1].replace(".action", "");
		openId=getCookieByName(getRequest(),"zjfmd_openId")!=null?getCookieByName(getRequest(),"zjfmd_openId").getValue():"";
//		openId="oiJJqxPseHI7Vo0Eay3R1jeELu4Q";
//		Cookie cookie=getCookieByName(getRequest(),"openId");
//		if(cookie==null){
//			cookie = new Cookie("openId",openId);
//			cookie.setMaxAge(60*60*1000);
//			//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
//			cookie.setPath("/");
//			getResponse().addCookie(cookie);
//		}	else {
//			cookie.setValue(openId);
//		}
		if(StringUtil.isNullOrEmpty(openId)&&tag){

			String actionName="check_checkLogin.action?page="+url;
			try {
				getResponse().sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeixinContons.APPID+"&redirect_uri=http%3a%2f%2f"+WeixinContons.WECHATHOST+"%2fzjfljkj_wechat%2f"+actionName+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect");
				//				getResponse().sendRedirect("http://www.baidu.com");
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return ERROR;
			}
		}else {
			return SUCCESS;
		}
	}

	/**
	 * 带参页面跳转
	 */
	public String forwardPageParam(){
		System.out.println("page:"+WeixinContons.APPID);
		String openId=null;
		String url=getRequest().getRequestURI().split("forwardPageParam_")[1].replace(".action", "");
		openId=getCookieByName(getRequest(),"zjfmd_openId")!=null?getCookieByName(getRequest(),"zjfmd_openId").getValue():"";
		String confing_parms="";
		if(parms!=null){
			confing_parms=parms.get("config")!=null?parms.get("config").toString():"";
		}
//						openId="1";
//						openId="oiJJqxPseHI7Vo0Eay3R1jeELu4Q";
//				Cookie cookie=getCookieByName(getRequest(),"openId");
//				if(cookie==null){
//					cookie = new Cookie("openId",openId);
//					cookie.setMaxAge(60*60*1000);
//					//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
//					cookie.setPath("/");
//					getResponse().addCookie(cookie);
//				}	else {
//					cookie.setValue(openId);
//				}
		if(StringUtil.isNullOrEmpty(openId)&&tag){
//			String actionName="check_checkLogin.action?page="+url;  
			String actionName="check_checkLogin.action?page="+url+"_"+confing_parms;
			try {
				getResponse().sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WeixinContons.APPID+"&redirect_uri=http%3a%2f%2f"+WeixinContons.WECHATHOST+"%2fzjfljkj_wechat%2f"+actionName+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect");
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return ERROR;
			}
		}else {
			return SUCCESS;
		}
	}
	/**
	 * 
	 * 校验登录信息
	 * @return
	 * @throws Exception
	 */
	public String checkLogin() {
		// 用户同意授权后，能获取到code
		String openId="";
		String code = getRequest().getParameter("code");
		String pageMap= getRequest().getParameter("page")!=null?getRequest().getParameter("page").toString():"";
		String page_url ="";
		String pags[]=pageMap.split("_");
		StringBuffer config=new StringBuffer();
		if(pags!=null&&pags.length>0){
			page_url =pags[0];
			for(int i=1;i<pags.length;i++){
				config.append(pags[i]);
				if(i!=(pags.length-1)){
				 config.append("_");
				}
			}
		}
		//				// 用户同意授权
		if (!"authdeny".equals(code)) {
			String weixin_code=getCookieByName(getRequest(),"zjfmd_weixin_code")!=null?getCookieByName(getRequest(),"zjfmd_weixin_code").getValue():"";

			if(weixin_code.equals(code)){
				openId=getCookieByName(getRequest(),"zjfmd_openId")!=null?getCookieByName(getRequest(),"zjfmd_openId").getValue():"";
			}else{
				// 获取网页授权access_token
				WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(WeixinContons.APPID, WeixinContons.APPSECRET, code);
				// 网页授权接口访问凭证
				String accessToken = weixinOauth2Token.getAccessToken();
				// 用户标识
				openId = weixinOauth2Token.getOpenId();
				
				SNSUserInfo userInfo=AdvancedUtil.getSNSUserInfo(accessToken,openId);
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("func_name", "saveWeixinUser");
				map.put("openId", openId);
				map.put("nickname",userInfo.getNickname());
				map.put("sex",userInfo.getSex());
				map.put("country",userInfo.getCountry());
				map.put("province",userInfo.getProvince());
				map.put("city",userInfo.getCity());
				map.put("headImgUrl",userInfo.getHeadImgUrl());
				String returnStr=OperationUtil.result(map);
				JSONObject jsonpara = JSONObject.parseObject(returnStr);
				if(jsonpara!=null&&jsonpara.size()>0){
					if(jsonpara.getIntValue("result")==0){
						result=1;
						JSONArray ary=JSON.parseArray(jsonpara.getString("dataList"));
						resultData.put("datalist", ary);
						resultData.put("size", ary!=null?ary.size():0);
					}else {
						result=0;
						if(jsonpara.getString("errmessage")!=null){
							msg=jsonpara.getString("errmessage");
						}else {
							msg="未获取到符合条件的数据";
						}
					}
				}else {
				}

				Cookie cookie=getCookieByName(getRequest(),"zjfmd_openId");
				Cookie cookie_weixincode=getCookieByName(getRequest(),"zjfmd_weixin_code");
				if(cookie==null){
					cookie = new Cookie("zjfmd_openId",openId);
					cookie.setMaxAge(60*60*1000);
					//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
					cookie.setPath("/");
					getResponse().addCookie(cookie);
				}	else {
					cookie.setValue(openId);
					getResponse().addCookie(cookie);
				}
				if(cookie_weixincode==null){
					cookie_weixincode = new Cookie("zjfmd_weixin_code",code);
					cookie.setMaxAge(60*60*1000);
					//设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
					cookie_weixincode.setPath("/");
					getResponse().addCookie(cookie_weixincode);
				}	else {
					cookie_weixincode.setValue(code);
					getResponse().addCookie(cookie);
				}	
			}
			page=page_url;
			if(parms!=null){
				parms.put("config",config.toString());
			}else {
				parms=new HashMap<String, String>();
				parms.put("config",config.toString());
			}
			try {
				getResponse().sendRedirect("forwardPageParam_"+page_url+".action?parms.config="+config.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
//		return SUCCESS;
		return null;
	}
}
